<?php
namespace app\api\model\wine;

use app\common\model\BaseModel;
use think\model\relation\OneToOne;
use think\Paginator;

class Collect extends BaseModel{
    protected $autoWriteTimestamp = true;

    // 关联项目
    public function project(): OneToOne
    {
        return $this->hasOne(Project::class, 'id', 'project_id')
            ->with(['illness', 'hospital'])
            ->bind(['sex', 'title', 'tag', 'allowance', 'gold', 'end_time', 'province_h', 'city_h', 'area_h', 'name_h']);
    }

    // 已收藏项目列表
    public static function getList(int $user_id): Paginator
    {
        return self::where(['user_id' => $user_id, 'is_delete' => 0])
            ->with('project')
            ->paginate(15);
    }

    /**
     * @param array $params
     * @return Collect|bool|\think\Model
     * @throws \app\common\exception\BaseException
     */
    public static function collected(array $params)
    {
        $r = self::where(['user_id' => $params['user_id'], 'project_id' => $params['project_id']])->findOrEmpty();
        if ($r->isEmpty()) {
            return self::create([
                'store_id' => getStoreId(),
                'user_id' => $params['user_id'],
                'project_id' => $params['project_id']
            ]);
        } else {
            throwError('你已经收藏了', 500);
        }
        return true;
    }

    // 取消收藏项目
    public static function unfavorite(array $params): bool
    {
        return self::where(['user_id' => $params['user_id'], 'project_id' => $params['project_id']])->delete();
    }
}
